<template>
  <el-form :model="cmsArticle" label-width="100px" :rules="rules" ref="formRef">
    <el-form-item label="标题" prop="title">
      <el-input v-model="cmsArticle.title" />
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input-number v-model="cmsArticle.sort" :min="1" :max="1000" />
    </el-form-item>
    <el-form-item label="主图" prop="image">
      <ImageUpload v-model="cmsArticle.image" :limit="1" />
    </el-form-item>
    <el-form-item label="分类" prop="categoryId" v-if="hasCategory">
      <SelectCategory @update:modelValue="handleCategoryId" v-model:modelValue="cmsArticle.categoryId" />
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'
const { proxy } = getCurrentInstance()
import ImageUpload from '@/components/ImageUpload/index.vue'
import SelectCategory from '../selectCategory/index.vue'

const props = defineProps({
  defaultData: {
    type: Object,
    default: () => { }
  },
  hasCategory: {
    type: Boolean,
    default: true
  }
})
const cmsArticle = ref({
  title: '',
  sort: 1,
  categoryId: '',
  image: ''
})

const rules = ref({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  image: [{ required: true, message: '请上传主图', trigger: 'change' }]
})

// 选择分类操作
const handleCategoryId = (categoryId) => {
  cmsArticle.value.categoryId = categoryId
}
// 提供一个方法让父组件获取 formRef
const getBaseFormRef = () => {
  return proxy.$refs["formRef"]
}
watch(() => props.defaultData, (newVal) => {
  cmsArticle.value = newVal
  cmsArticle.value.image = JSON.parse(newVal.image)
})
// 暴露方法给父组件使用
defineExpose({
  getBaseFormRef,
  cmsArticle
})
</script>

<style scoped></style>